package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderServiceImpl elderService;
    @Autowired
    private BedServiceImpl bedService;
    @Autowired
    private ContractServiceImpl contractService;
    @Autowired
    private CheckInConfigServiceImpl checkInConfigService;
    @Autowired
    private CheckInServiceImpl checkInService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //校验老人是否入住
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo())
                .one();
        if (elder != null && elder.getStatus() == 1){
            throw new RuntimeException("该老人已入住");
        }

        // 更新床位状态为已入住
        Bed bed = new Bed();
        bed.setBedStatus(1);
        bed.setId(dto.getCheckInConfigDto().getBedId());
        bedService.updateById(bed);
        //根据bed id 查询床位信息
        Bed bedInfo = bedService.selectBedById(dto.getCheckInConfigDto().getBedId());
        // 新增或更新老人
        if (bedInfo == null){
            throw new RuntimeException("床位不存在");
        }
        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        newElder.setStatus(1);
        newElder.setBedNumber(bedInfo.getBedNumber());
        newElder.setBedId(bedInfo.getId());
        if (elder != null ){
            newElder.setId(elder.getId());
        }
        elderService.saveOrUpdate(newElder);
        // 新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newElder.getId());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(LocalDateTime.now().isAfter(contract.getStartDate())?1:0);
        contractService.save(contract);
        // 新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(newElder.getId());
        checkIn.setElderName(newElder.getName());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setBedNumber(bedInfo.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkInService.save(checkIn);
        // 新增入住配置
        CheckInConfig bean = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        bean.setCheckInId(checkIn.getId());

        checkInConfigService.save(bean);
    }

    /**
     *  详情
     * @param id
     * @return
     */

    @Override
    public CheckInDetailVo detail(Long id) {
        // 查询入住信息
        CheckIn checkIn = checkInService.getById(id);
        // 查询老人信息

        Elder elder = elderService.getById(checkIn.getElderId());
//        CheckInElderVo checkInElderVo = new CheckInElderVo();
//        checkInElderVo.setId(elder.getId());
//        checkInElderVo.setName(elder.getName());
//        checkInElderVo.setIdCardNo(elder.getIdCardNo());
        // 查询合同
        Contract one = contractService.lambdaQuery().eq(Contract::getElderId, checkIn.getElderId()).one();
        // 查询入住配置
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()).one();

        // 转换家属列表
        List<ElderFamilyVo > familyList = JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
        // 整合数据返回
        CheckInDetailVo detailVo = new CheckInDetailVo();
        detailVo.setCheckInElderVo(BeanUtil.toBean(elder, CheckInElderVo.class));
        detailVo.setElderFamilyVoList(familyList);
        detailVo.setContract(one);
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
            // 设置开始时间和结束时间（从checkInConfig中获取）
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());

            // 设置床位信息（从checkIn中获取）
            checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        detailVo.setCheckInConfigVo(checkInConfigVo);

        return detailVo;
    }
}
